#include <logger.h>
#include <time.h>
#include <iostream>
Logger::Logger()
{
    // 启动写日志线程
    std::thread writeTask([&]()
                          {
        for(;;){
            // 获取当天的信息，写入日志信息，以追加的方式进行写入
            time_t now=time(nullptr);
            tm *nowtm=localtime(&now);
            char file_name[128];
            sprintf(file_name,"./%d-%d-%d-log.txt",nowtm->tm_year+1900,nowtm->tm_mon+1,nowtm->tm_mday);
            FILE *file=fopen(file_name,"a+");
            if(file==nullptr){
                std::cout<<"logger file: "<<file_name<<" open error!"<<std::endl;
                exit(EXIT_FAILURE);
            }
            std::string msg=m_lckQue.Pop();
            char time_buf[128]={0};
            sprintf(time_buf,"%d:%d:%d => [%s] ",
                nowtm->tm_hour,
                nowtm->tm_min,
                nowtm->tm_sec,
                (m_loglevel==INFO?"info":"error"));
            msg.insert(0,time_buf);
            msg.append("\n");

            fputs(msg.c_str(),file);
            fclose(file);
        } });
    writeTask.detach(); // 设置分离线程，忘记了
}
void Logger::SetLogLevel(LogLevel level)
{
    m_loglevel = level;
}
void Logger::Log(std::string msg)
{
    // 把日志写入到缓冲区中
    m_lckQue.Push(msg);
}
Logger &Logger::GetInstance()
{
    static Logger logger;
    return logger;
}